import axios, { AxiosInstance } from 'axios';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Session } from '/@/utils/storage';
import { ElLoading } from 'element-plus';
import qs from 'qs';
import settings from '/@/common/settings';
import { RSAEncrypt } from '/@/utils/encryption';
const sign = () => {
	let token = Session.get('UserToken');
	if (!token) {
		token = '';
	}
	let text = token + settings.signKey;
	return RSAEncrypt(text, settings.rsaPublicKey);
};

// 配置新建一个 axios 实例
const service: AxiosInstance = axios.create({
	baseURL: import.meta.env.VITE_API_URL,
	timeout: 50000,
	headers: { 'Content-Type': 'application/json' },
	paramsSerializer: {
		serialize(params) {
			return qs.stringify(params, { allowDots: true });
		},
	},
	transformRequest: [
		function (data, headers) {
			//data.Sign=sign(data)
			headers.set('sign', sign());
			return JSON.stringify(data);
		},
	],
});
let loading: any;
// 添加请求拦截器
service.interceptors.request.use(
	(config) => {
		loading = ElLoading.service({
			lock: true,
			text: 'Loading',
			background: 'rgba(0, 0, 0, 0.7)',
		});
		// 在发送请求之前做些什么 token
		config.headers!['Authorization'] = 'Bearer ' + Session.get('UserToken');
		return config;
	},
	(error) => {
		loading = ElLoading.service({
			lock: true,
			text: 'Loading',
			background: 'rgba(0, 0, 0, 0.7)',
		});
		// 对请求错误做些什么
		return Promise.reject(error);
	}
);

// 添加响应拦截器
service.interceptors.response.use(
	(response) => {
		if (loading) {
			loading.close();
		}
		return response.data;
	},
	(error) => {
		if (loading) {
			loading.close();
		}
		let errorMsg = '';
		if (error.response?.status == 401) {
			ElMessageBox.confirm('登录状态已过期，请重新登录', '系统提示', {
				confirmButtonText: '重新登陆',
				cancelButtonText: '取消',
				type: 'warning',
			}).then(() => {
				Session.set('UserToken', null);
				window.location.href = '/';
			});
		} else if (error.response?.status == 403) {
			window.location.href = '/403';
		} else if (error.response?.status == 404) {
			window.location.href = '/404';
		} else if (error.message == 'Network Error') {
			errorMsg = '网络连接异常';
		} else if (error.message.includes('timeout')) {
			errorMsg = '网络请求超时';
		} else {
			errorMsg = error.message;
		}
		if (errorMsg != '') {
			ElMessage({
				message: errorMsg,
				type: 'error',
				duration: 3000,
				showClose: true,
				grouping: true,
			});
		}

		return Promise.reject();
	}
);

// 导出 axios 实例
export default service;
